#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/time.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <getopt.h>

#include <linux/input.h>
#include <sys/ioctl.h>
#include <tslib.h>

#include "gesture.h"
#include "track.h"

int main(int argc,int **argv)
{
    struct tsdev *ts;
    struct ts_sample_mt **samp_mt;
    struct input_absinfo slot;
    int *touch_id;
    int ret;

    int touch = 0;

    ts = ts_setup(NULL,0);
    if(!ts)
    {
        printf("ts_setup err!\n");
        return -1;
    }

     //通过以下代码寻找触摸屏的最大slot信息
     if (ioctl(ts_fd(ts), EVIOCGABS(ABS_MT_SLOT), &slot) < 0) {
		perror("ioctl EVIOGABS");
		ts_close(ts);
		return errno;
	}

	int max_slots = slot.maximum + 1 - slot.minimum;    //获得屏幕支持的最多触点的数据   
    printf("max_slots = %d\n",max_slots);

    samp_mt = malloc(sizeof(struct ts_sample_mt *));
    if (!samp_mt) {
		ts_close(ts);
		return -ENOMEM;
	}

    samp_mt[0] = calloc(max_slots,sizeof(struct ts_sample_mt));
    if(samp_mt[0] == NULL)
    {
        free(samp_mt);
        ts_close(ts);
		return -ENOMEM;
    }

    touch_id = malloc(sizeof(int) * max_slots); 
    if(touch_id == NULL)
    {
        free(samp_mt[0]);
        free(samp_mt);
        ts_close(ts);
    }

    init_touch_points(max_slots);
    
    while(1)
    {
        ret = ts_read_mt(ts,samp_mt,max_slots,1);
        if(ret < 0)
        {
            printf("ts_read_mt error!\n");
			goto err;
        }

        proc_gesture(samp_mt);

    }

err:
    exit_touch_points();
    free(samp_mt[0]);
    free(samp_mt);
    ts_close(ts);
    return -1;
}
